<template>
  <el-dialog
    :title="showNew ? (dataForm.id ? '修改产品': '新建产品' ) : '产品信息'"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    :visible.sync="visible"
    :fullscreen="true">
    <div v-show="!showNew">
      <el-table
        :data="dataList"
        border
        stripe
        v-loading="dataListLoading"
        @selection-change="selectionChangeHandle"
        :height=tableHeight
        style="width: 100%;">
        <el-table-column
          fixed="left"
          header-align="center"
          align="left"
          type="index"
          width="50">
        </el-table-column>
        <el-table-column
          type="selection"
          header-align="center"
          align="center"
          width="50">
        </el-table-column>
        <el-table-column
          prop="goodsId"
          header-align="center"
          align="center"
          label="商品序列号"
          width="130">
        </el-table-column>
        <el-table-column
          prop="goodsName"
          header-align="center"
          align="center"
          label="商品">
        </el-table-column>
        <el-table-column
          prop="specificationValue"
          header-align="center"
          align="center"
          label="产品规格">
        </el-table-column>
        <el-table-column
          prop="goodsNumber"
          header-align="center"
          align="center"
          label="产品库存"
          width="130">
        </el-table-column>
        <el-table-column
          prop="retailPrice"
          header-align="center"
          align="center"
          label="零售价格(元)"
          width="130">
        </el-table-column>
        <el-table-column
          prop="marketPrice"
          header-align="center"
          align="center"
          label="市场价格(元)"
          width="130">
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          label="操作"
          width="100">
          <template slot-scope="scope">
            <el-button v-if="isAuth('product:update')" type="text" size="small" @click="showNewView(scope.row)">修改</el-button>
            <el-button v-if="isAuth('product:delete')" type="text" size="small" @click="deleteHandle(scope.row.id)" class="delete-button">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="showNew">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="100px">
        <el-form-item label="商品库存" prop="goodsNumber">
          <el-input-number v-model="dataForm.goodsNumber" controls-position="right" :min="0" label="商品库存" type="number"></el-input-number>
        </el-form-item>
        <el-form-item label="零售价格" prop="retailPrice">
          <el-input-number v-model="dataForm.retailPrice" controls-position="right" :min="0" label="零售价格" type="number"></el-input-number>
        </el-form-item>
        <el-form-item label="市场价" prop="marketPrice">
          <el-input-number v-model="dataForm.marketPrice" controls-position="right" :min="0" label="市场价" type="number"></el-input-number>
        </el-form-item>
        <el-form-item :label="value.name" v-for="(value,index) in goodsSpecifications" :key="index">
          <el-select
            clearable
            v-model="value.value"
            :placeholder="'请选择' + value.name"
            style="width: 100%;">
            <el-option
              v-for="item in value.list"
              :key="item.id"
              :label="item.value"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <!--新建页控制按钮-->
    <span slot="footer" class="dialog-footer" v-show="showNew">
        <el-button type="primary" @click="dataFormSubmit()">提交</el-button>
        <el-button @click="hideNewView()">取消</el-button>
    </span>
    <!--主页控制按钮-->
    <span slot="footer" class="dialog-footer" v-show="!showNew">
      <el-button v-if="isAuth('product:save')" type="primary" @click="showNewView()">新建</el-button>
      <el-button v-if="isAuth('product:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
      <el-button @click="cancel()">返回</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        // 对话框是否显示
        visible: false,
        dataList: [],
        dataListLoading: false,
        showNew: false,
        dataForm: {
          id: 0,
          goodsId: '',
          goodsNumber: '',
          marketPrice: '',
          retailPrice: ''
        },
        dataRule: {
          goodsNumber: [
            { required: true, message: '库存不能为空', trigger: 'blur' }
          ],
          marketPrice: [
            { required: true, message: '市场价不能为空', trigger: 'blur' }
          ],
          retailPrice: [
            { required: true, message: '零售价不能为空', trigger: 'blur' }
          ]
        },
        // 多选项集合
        dataListSelections: [],
        // 商品规格列表
        goodsSpecifications: []
      }
    },
    computed: {
      tableHeight: function () {
        return this.$store.state.common.documentClientHeight - 180
      }
    },
    methods: {
      // 初始化
      init (goodsId) {
        this.dataForm.goodsId = goodsId
        this.getDataList()
        this.visible = true
      },
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/back/product/list'),
          method: 'get',
          params: this.$http.adornParams({
            'goodsId': this.dataForm.goodsId
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.data.list
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      // 显示新建/修改表单
      showNewView (product) {
        if (product) {
          this.dataForm.id = product.id
          this.dataForm.goodsNumber = product.goodsNumber
          this.dataForm.marketPrice = product.marketPrice
          this.dataForm.retailPrice = product.retailPrice
          this.getGoodsSpecifications(product.goodsSpecificationIds)
        } else {
          this.getGoodsSpecifications()
        }
        this.showNew = true
      },
      // 隐藏新建/修改表单
      hideNewView () {
        this.showNew = false
        this.dataForm.id = 0
        this.dataForm.goodsNumber = ''
        this.dataForm.marketPrice = ''
        this.dataForm.retailPrice = ''
      },
      // 获取商品规格列表
      getGoodsSpecifications (goodsSpecificationIds) {
        var ids = []
        if (goodsSpecificationIds) {
          ids = goodsSpecificationIds.split('_')
        }
        this.$http({
          url: this.$http.adornUrl('/back/goodsSpecification/list'),
          method: 'get',
          params: this.$http.adornParams({
            'goodsId': this.dataForm.goodsId
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            var specifications = ''
            var result = []
            data.data.list.map(function (value, i) {
              if (specifications.indexOf(value.specificationId) === -1) {
                specifications += value.specificationId + '_'
                var specification = {
                  id: value.specificationId,
                  name: value.specificationName,
                  value: '',
                  list: []
                }
                specification.list = data.data.list.filter(function (item) {
                  if (item.specificationId === value.specificationId) {
                    if (ids) {
                      ids.map(function (value2, j) {
                        if (value2 == item.id) {
                          specification.value = item.id
                        }
                      })
                    }
                    return item
                  }
                })
                result.push(specification)
              }
            })
            this.goodsSpecifications = result
          } else {
            this.goodsSpecifications = []
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            var goodsSpecificationIds = []
            this.goodsSpecifications.map(function (value, i) {
              if (value.value) {
                goodsSpecificationIds.push(value.value)
              }
            })
            this.$http({
              url: this.$http.adornUrl(`/back/product/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                id: this.dataForm.id || undefined,
                goodsId: this.dataForm.goodsId,
                goodsSn: this.dataForm.goodsId,
                goodsNumber: this.dataForm.goodsNumber,
                marketPrice: this.dataForm.marketPrice,
                retailPrice: this.dataForm.retailPrice,
                goodsSpecificationIds: goodsSpecificationIds.sort().join('_')
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.showNew = false
                this.getDataList()
                this.dataForm.id = 0
                this.dataForm.goodsNumber = ''
                this.dataForm.marketPrice = ''
                this.dataForm.retailPrice = ''
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/back/product/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }).catch(() => {})
      },
      // 取消操作
      cancel () {
        var that = this
        that.$emit('closeDialog')
        that.visible = false
      }
    }
  }
</script>

<style>
  .delete-button{
    color:#F56C6C;
  }
</style>
